#include "lte_service.h"
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include <stddef.h>

#define RESPONSE_BUFFER_SIZE 1024
#define DEFAULT_TIMEOUT_MS 5000

int serial_fd;

int serial_init(const char *device) {
    serial_fd = open(device, O_RDWR | O_NOCTTY); // 以阻塞模式打开串口[3](@ref)
    if (serial_fd == -1) {
        perror("Error opening serial port");
        return -1;
    }

    struct termios options;
    tcgetattr(serial_fd, &options);
    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);

    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;

    options.c_cc[VMIN] = 1;  // 阻塞模式，直到收到至少1个字符[3](@ref)
    options.c_cc[VTIME] = 10; // 设置超时

    if (tcsetattr(serial_fd, TCSANOW, &options) != 0) {
        perror("Error setting serial options");
        close(serial_fd);
        return -1;
    }
    return 0;
}


int send_at_command(int fd, const char *command, char *response_prefix, char *response, size_t response_size) {
    char temp_buffer[RESPONSE_BUFFER_SIZE];
    int bytes_read;
    int total_bytes = 0;
    time_t start_time = time(NULL);
    // 清空接收缓冲区
    tcflush(fd, TCIFLUSH);

    // 发送AT指令（注意添加回车换行）
    int bytes_written = write(fd, command, strlen(command));
    write(fd, "\r\n", 2); // 确保指令以回车换行结束[4](@ref)
    if (bytes_written < 0) {
        perror("Error writing to serial port");
        return -1;
    }
    // 读取响应
    memset(temp_buffer, 0, sizeof(temp_buffer));
    memset(response, 0, response_size);
    while ((time(NULL) - start_time) * 1000 < DEFAULT_TIMEOUT_MS) {
        bytes_read = read(fd, temp_buffer + total_bytes, sizeof(temp_buffer) - total_bytes - 1);
        if (bytes_read > 0) {
            total_bytes += bytes_read;
            temp_buffer[total_bytes] = '\0';

            // 检查是否收到最终响应"OK"或"ERROR"[1](@ref)
            if (strstr(temp_buffer, "OK") != NULL || strstr(temp_buffer, "ERROR") != NULL) {
                break;
            }
        } else if (bytes_read < 0) {
            perror("Error reading from serial port");
            return -1;
        }
        usleep(100000); // 延迟100ms再读，避免频繁轮询[1](@ref)
    }
    // 处理响应，例如查找特定前缀
    if (response_prefix != NULL) {
        char *prefix_ptr = strstr(temp_buffer, response_prefix);
        if (prefix_ptr) {
            // 提取前缀后的数据（简化处理，实际应用需更严谨解析）
            char *data_start = prefix_ptr + strlen(response_prefix);
            char *line_end = strchr(data_start, '\r');
            if (line_end) {
                *line_end = '\0';
            }
            strncpy(response, data_start, response_size - 1);
        } else {
            return -1; // 未找到预期响应前缀
        }
    } else {
        if (response != NULL && response_size > 0)
        {
            strncpy(response, temp_buffer, response_size - 1);
        }
    }
    return 0;
}
// 解析函数
int parseQENG(const char* response, ServingCellInfo* info) {
    // 初始化结构体，确保所有字段都有默认值
    memset(info, 0, sizeof(ServingCellInfo));

    // 检查响应中是否包含"+QENG:"关键字[7](@ref)
    // const char* start = strstr(response, "+QENG:");
    // if (start == NULL) {
    //     printf("Error: Not a +QENG response.\n");
    //     return -1;
    // }
    printf("response: %s\n", response);
    // 使用sscanf解析数据，注意处理引号和十六进制字符串[6,7](@ref)
    int parsed_count = sscanf(response,
        " \"%15[^\"]\",\"%15[^\"]\",\"%7[^\"]\",\"%7[^\"]\",%d,%d,%x,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
        info->mode,
        info->state,
        info->rat,
        info->duplex_mode,
        &info->mcc,
        &info->mnc,
        &info->cell_id,  // 直接解析为十六进制数
        &info->pci,
        &info->earfcn,
        &info->ul_bandwidth,
        &info->dl_bandwidth,
        &info->tac,
        &info->rsrp,
        &info->rsrq,
        &info->sinr,
        &info->cqi,
        &info->tx_power,
        &info->srxlev);

    // 检查是否成功解析了所有18个字段
    if (parsed_count != 18) {
        printf("Error: Parsed %d fields, expected 18.\n", parsed_count);
        return -1;
    }

    return 0;
}
